from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from typing import List
from app.database import get_db
from app.models import KnowledgeBase, User
from app.schemas import KnowledgeBaseCreate, KnowledgeBaseUpdate, KnowledgeBaseResponse
from app.core.deps import get_current_active_user
from app.core.logging import logger

router = APIRouter(prefix="/knowledge-bases", tags=["knowledge-bases"])

@router.post("/", response_model=KnowledgeBaseResponse)
async def create_knowledge_base(
    knowledge_base: KnowledgeBaseCreate,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """创建知识库"""
    logger.info(f"用户 {current_user.username} 创建知识库: {knowledge_base.name}")
    
    db_knowledge_base = KnowledgeBase(
        **knowledge_base.dict(),
        user_id=current_user.id
    )
    
    db.add(db_knowledge_base)
    await db.commit()
    await db.refresh(db_knowledge_base)
    
    logger.info(f"知识库创建成功: {knowledge_base.name}")
    return db_knowledge_base

@router.get("/", response_model=List[KnowledgeBaseResponse])
async def get_knowledge_bases(
    skip: int = 0,
    limit: int = 100,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取用户的知识库列表"""
    logger.info(f"用户 {current_user.username} 获取知识库列表")
    
    result = await db.execute(
        select(KnowledgeBase)
        .where(KnowledgeBase.user_id == current_user.id)
        .offset(skip)
        .limit(limit)
    )
    
    knowledge_bases = result.scalars().all()
    return knowledge_bases

@router.get("/{knowledge_base_id}", response_model=KnowledgeBaseResponse)
async def get_knowledge_base(
    knowledge_base_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """获取指定知识库"""
    logger.info(f"用户 {current_user.username} 获取知识库 {knowledge_base_id}")
    
    result = await db.execute(
        select(KnowledgeBase)
        .where(KnowledgeBase.id == knowledge_base_id)
        .where(KnowledgeBase.user_id == current_user.id)
    )
    
    knowledge_base = result.scalar_one_or_none()
    if not knowledge_base:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Knowledge base not found"
        )
    
    return knowledge_base

@router.put("/{knowledge_base_id}", response_model=KnowledgeBaseResponse)
async def update_knowledge_base(
    knowledge_base_id: int,
    knowledge_base_update: KnowledgeBaseUpdate,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """更新知识库"""
    logger.info(f"用户 {current_user.username} 更新知识库 {knowledge_base_id}")
    
    result = await db.execute(
        select(KnowledgeBase)
        .where(KnowledgeBase.id == knowledge_base_id)
        .where(KnowledgeBase.user_id == current_user.id)
    )
    
    knowledge_base = result.scalar_one_or_none()
    if not knowledge_base:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Knowledge base not found"
        )
    
    # 更新字段
    update_data = knowledge_base_update.dict(exclude_unset=True)
    for field, value in update_data.items():
        setattr(knowledge_base, field, value)
    
    await db.commit()
    await db.refresh(knowledge_base)
    
    logger.info(f"知识库更新成功: {knowledge_base_id}")
    return knowledge_base

@router.delete("/{knowledge_base_id}")
async def delete_knowledge_base(
    knowledge_base_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """删除知识库"""
    logger.info(f"用户 {current_user.username} 删除知识库 {knowledge_base_id}")
    
    result = await db.execute(
        select(KnowledgeBase)
        .where(KnowledgeBase.id == knowledge_base_id)
        .where(KnowledgeBase.user_id == current_user.id)
    )
    
    knowledge_base = result.scalar_one_or_none()
    if not knowledge_base:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Knowledge base not found"
        )
    
    await db.delete(knowledge_base)
    await db.commit()
    
    logger.info(f"知识库删除成功: {knowledge_base_id}")
    return {"message": "Knowledge base deleted successfully"}